'use strict';
const axios = require('axios');
const Controller = require('egg').Controller;

class userController extends Controller {
    async login() {
        const { ctx } = this;
        const { name, password, email } = ctx.request.body;
        //7、定制化校验添加校验自定义校验规则，校验邮箱
        const reuls = {
            name: 'string',
            password: "password",
            email: 'email'
        }
        if (!ctx.helper.Validata(reuls, ctx.request.body)) {
            const userDate = await ctx.service.user.getLogin(name, password, email);
            if (userDate) {
                const userObj = { ...userDate }
                const token = ctx.helper.token.sign(userObj)
                ctx.body = {
                    code: 200,
                    msg: "登录成功",
                    token
                }
            } else {
                ctx.body = {
                    code: 400,
                    msg: "登录失败用户名或密码错误"
                }
            }
        } else {
            ctx.body = {
                code: 400,
                msg: "登录失败,输入格式有误"
            }
        }
    }

    async gitlogin() {
        const { ctx } = this;
        const { code } = ctx.request.body;
        if (code) {
            const { gitee } = this.app.config;
            const res = await axios.post('https://gitee.com/oauth/token', {
                grant_type: 'authorization_code',
                code,
                client_id: gitee.client_id,
                client_secret: gitee.client_secret,
                redirect_uri: gitee.redirect_uri,
            })
            if (res.data.access_token) {
                const { access_token } = res.data
                //12、后端正确获取授权返回用户的三方信息
                const user = await axios.get('https://gitee.com/api/v5/user', { params: { access_token } });
                const { name, email } = user.data;
                const gitUser = { name, password: '123456', email }
                const token = ctx.helper.token.sign(gitUser);
                ctx.body = {
                    code: 200,
                    msg: '第三方登录成功',
                    gitUser: user.data,
                    token
                }
            } else {
                ctx.body = {
                    code: 402,
                    msg: '登录失败未获取到token',
                }
            }

        } else {
            ctx.body = {
                code: 401,
                msg: '未获取到code'
            }
        }
    }
}

module.exports = userController;
